import { defineStore } from 'pinia'
import { storageLocal, store, type UserStoreType } from '../util'
import type { UserAuthItem, UserInfo } from '@/utils/auth'
import type { LoginParams, RoleItem } from '@/api/types'
import { _login, _userInfo, _logout, _queryRoleAuth } from '@/api/auth'
export const useUserStore = defineStore('easy-user', {
  state: (): UserStoreType => ({
    userInfo: storageLocal().getItem<UserInfo<number>>('userInfo') ?? {
      id: null,
      name: null,
      nickname: null,
      phone: null,
      avatar: null,
      // expires: 7,
      roleCode: null,
      roleName: null,
      createTime: null,
      updateTime: null,
      description: null
    },
    accessToken: storageLocal().getItem('accessToken') || null,
    userAuth: null,
    menuAuth: new Set(),
    operationAuth: new Map(),
    verificationCode: ''
  }),
  getters: {
    nickName: state => state.userInfo.nickname
  },
  actions: {
    loginByUsername(data: LoginParams) {
      return new Promise<any>((resolve, reject) => {
        _login(data)
          .then(async res => {
            this.SET_ACCESS_TOKEN(res.data.access_token)
            await this.checkUserInfo()
            resolve(res)
          })
          .catch(err => {
            reject(err)
          })
      })
    },
    loginOut() {
      return new Promise((resolve, reject) => {
        _logout()
          .then(res => {
            this.clearLoginStatus()
            resolve(res)
          })
          .catch(err => {
            reject(err)
          })
      })
    },
    /**
     * @description 检查用户信息
     * @returns {Promise<{userInfo, auth}>}
     */
    checkUserInfo(): Promise<any> {
      return new Promise<any>((resolve, reject) => {
        _userInfo()
          .then(res => {
            this.SET_USERINFO(res.data.userInfo)
            this.SET_USERAUTH(res.data.auth)
            resolve(res)
          })
          .catch(err => {
            console.log(err)
            reject(err)
          })
      })
    },
    SET_USERAUTH(userAuth: Array<UserAuthItem>) {
      this.userAuth = userAuth
      this.menuAuth.clear()
      this.operationAuth.clear()
      if (!userAuth) return
      userAuth.forEach(auth => {
        this.menuAuth.add(auth.name)
        const opts = auth.operations ? auth.operations.split(',') : []
        this.operationAuth.set(auth.name, new Set(opts))
      })
    },
    SET_USERINFO(info: UserInfo<number>) {
      this.userInfo = Object.assign(this.userInfo, info)
      storageLocal().setItem('userInfo', this.userInfo)
    },
    SET_VERIFICATION_CODE(code: string) {
      this.verificationCode = code
    },
    SET_ACCESS_TOKEN(token: string) {
      this.accessToken = token
      storageLocal().setItem('accessToken', this.accessToken)
    },
    changeCurrentRole(role: RoleItem) {
      _queryRoleAuth(role.id).then(res => {
        this.SET_USERINFO({
          roleCode: role.code,
          roleName: role.name,
          roleId: role.id
        })
        this.SET_USERAUTH(res.data)
      })
    },
    /**
     * @description 清楚登陆状态
     */
    clearLoginStatus() {
      this.SET_USERINFO({
        id: null,
        name: null,
        nickname: null,
        phone: null,
        avatar: null,
        role: null,
        createTime: null,
        updateTime: null,
        description: null
      })
      this.SET_USERAUTH(null)
      this.SET_ACCESS_TOKEN(null)
      storageLocal().removeItem('userInfo')
      this.SET_ACCESS_TOKEN(null)
      storageLocal().removeItem('accessToken')
    }
  }
})

export function useUserStoreHook() {
  return useUserStore(store)
}
